import React from 'react';
import { withRouter, Link } from 'umi';
import { Form, Input, Row, Col, Card } from 'antd';
import isEmpty from 'lodash/isEmpty';
import { connect } from 'umi';

import { TitleControl } from '@/pages/Recruitment/components';
import InterviewRecords from '@/pages/Organization/EmployeeManage/components/EmployeeInfoSections/InterviewRecords';
import { usePositionAndRank } from '@/pages/Recruitment/Hire/hooks';

import { getSummary } from '@/pages/WorkFlow/Flow/utils';
import { styleTitle } from './util';
import { Talent, SuggestSalary, OriginSalary, HireInfo } from './containers';
import { useFlowData } from './hooks';
import styles from './index.less';

const Hire = ({ flowWaitApproval, flowMyApplication, location, form, formValueMap = {}, setSubmitLoading }) => {
    const processStatus = flowWaitApproval?.detailData?.processStatus || flowMyApplication?.detailData?.processStatus; // 1待发送 2审批中 3未通过 4已通过 5已撤销 6已退回
    const { query, pathname } = location;
    const hiDataId = query?.hiDataId || formValueMap?.hiDataId;

    const {
        talentInfo: originalTalentInfo,
        applyData = {},
        commInfo,
        hireInfo,
        recordInfo,
        loading: flowDataLoading
    } = useFlowData(hiDataId);

    const {
        positionName,
        positionCode,
        companyAreaCode,
        positionCodeChangeFlag,
        loading: positionAndRankLoading,
        employSalaryCurrencyCode,
        organizationName
    } = usePositionAndRank(applyData.employId);

    const talentInfo = { ...originalTalentInfo, positionName, positionCode, companyAreaCode, employSalaryCurrencyCode };

    applyData.organizationName = organizationName;

    const childProps = {
        talentInfo,
        applyData,
        commInfo,
        isEdit: isEmpty(formValueMap),
        form,
        formValueMap,
        hireInfo,
        recordInfo
    };

    // const { getFieldsValue, setFieldsValue } = form;
    // const formValue = getFieldsValue();
    // React.useEffect(() => {
    //     setFieldsValue({ salary: formValue?.month * formValue?.monthSalary || 0 });
    // }, [formValue?.month, formValue?.monthSalary]);

    const { setFieldsValue } = form;

    React.useEffect(() => {
        const summary = getSummary({
            候选人姓名: talentInfo.talentName,
            应聘岗位: applyData.entryDutyName,
            部门: applyData.organizationName,
            职位职级: positionName
        });
        setFieldsValue({ applicationAbstract: summary });
    }, [JSON.stringify(talentInfo), positionName, JSON.stringify(applyData)]);

    // 审批流程接口数据来源于getFieldsValue，并且在初始化时调用，不能使用initialValue
    React.useEffect(() => {
        setFieldsValue({ positionCodeChangeFlag });
    }, [positionCodeChangeFlag]);

    // 提交前要保证所有数据loading结束
    const loading = flowDataLoading || positionAndRankLoading;
    React.useEffect(() => {
        setSubmitLoading(loading);
    }, [loading]);

    const getClassName = path => {
        // 特定页面，特定样式。。。😓
        if (
            path === '/personal/portal/waitApproval/approvalDetail' ||
            path === '/personal/portal/myApplication/detail'
        ) {
            return styles.asFirstChild;
        }
        return null;
    };

    return (
        <Row>
            {processStatus >= 2 ? null : (
                <Row>
                    <span style={{ color: 'rgba(217, 0, 27)' }}>（注：请确认信息后，提交申请！）</span>
                </Row>
            )}
            <TitleControl title="候选人信息" titleRender={styleTitle} className={getClassName(pathname)}>
                <Talent {...childProps} />
            </TitleControl>
            <TitleControl title="面试记录" titleRender={styleTitle}>
                <InterviewRecords formData={recordInfo} excludeColumn={['operateEmployeeName']} />
            </TitleControl>
            <TitleControl title="薪资信息" titleRender={styleTitle}>
                <Row style={{ padding: '8px 16px' }} gutter={[0, 16]}>
                    <Col>
                        <Card title="原薪资信息" type="inner">
                            <OriginSalary {...childProps} />
                        </Card>
                    </Col>
                    <Col>
                        <Card
                            title="建议薪资"
                            extra={
                                <Link
                                    to={{
                                        pathname: '/office/personnelManagement/recruitment/hire/detail',
                                        query: { candidateId: applyData?.candidateId, employId: applyData?.employId }
                                    }}
                                >
                                    薪资沟通详情
                                </Link>
                            }
                            type="inner"
                        >
                            <SuggestSalary {...childProps} isEdit={false} />
                        </Card>
                    </Col>
                </Row>
            </TitleControl>
            <TitleControl title="录用信息" titleRender={styleTitle}>
                <HireInfo {...childProps} isEdit={false} />
            </TitleControl>

            <Row>
                {/* 所有流程前置数据关联 */}
                <Form.Item style={{ display: 'none' }}>
                    {form.getFieldDecorator('hiDataId', {
                        initialValue: hiDataId
                    })(<Input />)}
                </Form.Item>
                {/* 摘要 */}
                <Form.Item style={{ display: 'none' }}>
                    {form.getFieldDecorator('applicationAbstract')(<Input />)}
                </Form.Item>
                <Form.Item style={{ display: 'none' }}>
                    {form.getFieldDecorator('positionCodeChangeFlag')(<Input />)}
                </Form.Item>
            </Row>
        </Row>
    );
};

export default withRouter(
    connect(({ flowWaitApproval, flowMyApplication }) => ({
        flowWaitApproval,
        flowMyApplication
    }))(Hire)
);

// export default withRouter(Hire);
